package com.d0319.Z19;

public class Money2 {
    Object obj=new Object();
    int money=1000;
    public void Guitai(){
        while(money>0) {
            synchronized (obj){
                Thread.currentThread().setName("A");
                System.out.println(Thread.currentThread().getName() + "在柜台取走" + 100 + "元" + " ");
                money = money - 100;
                System.out.println("剩余钱数：" + money + "元");
                try{
                        //Thread.sleep(100);
                        obj.wait(100);//将线程B进入阻塞状态
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public void ATM(){
        while(money>0){
            synchronized (obj){
                Thread.currentThread().setName("B");
                System.out.println(Thread.currentThread().getName()+"在ATM取走"+100+"元"+" ");
                money=money-100;
                System.out.println("剩余钱数：" + money + "元");

                    try {
                        obj.wait(100);//将线程B进入阻塞状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        }

    }
    public void save() {
        while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                    Thread.currentThread().setName("C用户");
                    System.out.println(Thread.currentThread().getName() + "存入" + 2000+ "元"+" ");
                    money=money+2000;
                    System.out.println("剩余钱数:" + money + "元");
                synchronized (obj) {
                    obj.notify();//随机唤醒A或B线程
            }
        }
    }
    public static void main(String[] args) {
        Money2 mon=new Money2();
        new Thread(()->mon.Guitai()).start();
        new Thread(()->mon.ATM()).start();
        new Thread(()->mon.save()).start();
    }
}
